package com.ksyzt.ksite2.server.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLException;

import javax.mail.internet.MimeUtility;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ksyzt.ksite2.server.common.Application;
import com.ksyzt.ksite2.server.database.dao.IATTACHMENTDAO;
import com.ksyzt.ksite2.server.database.dao.impl.ATTACHMENTDAOImpl;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObj;

public class Attatchment extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Application app = new Application(request, response);
		String tag = app.parameterAsString("tag", "");

		IATTACHMENTDAO dao = new ATTACHMENTDAOImpl(Application.getConnection());
		ATTACHMENTObj att = null;
		try {
			att = dao.findByTAG(tag);
		} catch (SQLException e) {
			e.printStackTrace();
			renderHTML(response, "error:" + e.getMessage());
			return;
		}
		if (att == null) {
			renderHTML(response, "您要下载的文件暂时不能提供下载?");
			return;
		} else {
			String title = att.getTITLE();
			String root = request.getRealPath("/");
			String local = root + att.getFILEPATH();

			File f = new File(local);
			if (f.exists()) {
				response.reset();
				response.setContentType(att.getFTYPE());
				response.setCharacterEncoding("UTF-8");
				System.out.println(title);
				String userAgent = request.getHeader("User-Agent");
				String name = translateFileName(userAgent, title);
				response.addHeader("Content-Disposition",
						"attachment; filename=\"" + name + "\"");
				System.out.println(name);
				int fileLength = (int) f.length();
				response.setContentLength(fileLength);
				/* 如果文件长度大于0 */
				if (fileLength != 0) {
					/* 创建输入流 */
					InputStream inStream = new FileInputStream(f);
					byte[] buf = new byte[4096];
					/* 创建输出流 */
					ServletOutputStream servletOS = response.getOutputStream();
					int readLength;
					while (((readLength = inStream.read(buf)) != -1)) {
						servletOS.write(buf, 0, readLength);
					}
					inStream.close();
					servletOS.flush();
					servletOS.close();

					Integer c = att.getDCOUNT();
					if (c == null) {
						c = 1;
					} else {
						c = c + 1;
					}
					att.setDCOUNT(c);
					try {
						dao.updateObjectByPK(att);
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			} else {
				renderHTML(response,
						"您要下载的文件暂时不能提供下载?Server says the file does not exist:"
								+ local);
			}
		}

	}

	private String translateFileName(String userAgent, String name)
			throws UnsupportedEncodingException {
		String new_filename = URLEncoder.encode(name, "UTF8");
		// 如果没有UA，则默认使用IE的方式进行编码，因为毕竟IE还是占多数的
		String rtn = "filename=\"" + new_filename + "\"";

		if (userAgent != null) {
			userAgent = userAgent.toLowerCase();
			// IE浏览器，只能采用URLEncoder编码
			if (userAgent.indexOf("msie") != -1) {
				rtn = "filename=\"" + new_filename + "\"";
			}
			// Opera浏览器只能采用filename*
			else if (userAgent.indexOf("opera") != -1) {
				rtn = "filename*=UTF-8''" + new_filename;
			}
			// Safari浏览器，只能采用ISO编码的中文输出
			else if (userAgent.indexOf("safari") != -1) {
				rtn = "filename=\""
						+ new String(name.getBytes("UTF-8"), "ISO8859-1")
						+ "\"";
			}
			// Chrome浏览器，只能采用MimeUtility编码或ISO编码的中文输出
			else if (userAgent.indexOf("applewebkit") != -1) {
				new_filename = MimeUtility.encodeText(name, "UTF8", "B");
				rtn = "filename=\"" + new_filename + "\"";
			}
			// FireFox浏览器，可以使用MimeUtility或filename*或ISO编码的中文输出
			else if (userAgent.indexOf("mozilla") != -1) {
				rtn = "filename*=UTF-8''" + new_filename;
			}
		}

		return rtn;
	}

	private void renderHTML(HttpServletResponse response, String msg) {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>下载附件</TITLE></HEAD>");
		out.println("  <BODY>");
		out.println("<h1>" + msg + "</h1>");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
}
